/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.xjw.tool;

import com.xjw.mapper.ChessMapper;

import cn.hutool.core.io.FileUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static final Log LOG = LogFactory.get("MybatisUtils:");

    private static SqlSessionFactory sqlSessionFactory;

    private static SqlSession sqlSession;

    // 静态代码块 预加载 获取 SqlSessionFactory对象
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            LOG.error(e);
        }

    }


    public static boolean testConnect(){
        return testSqlSession(getSqlSession());
    }

    public static boolean reLoadResource(String filePath){
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(FileUtil.getInputStream(FileUtil.file(filePath)));
            sqlSession = sqlSessionFactory.openSession(true);
            return testSqlSession(sqlSession);
        } catch (Exception e) {
            LOG.error("fail to reLoadResource:",e);
            return false;
        }
    }

    /**
     * 既然有了 SqlSessionFactory，顾名思义，我们可以从中获得 SqlSession 的实例。
     * SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
     * 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
     * @return SqlSession
     */
    public static SqlSession getSqlSession(){
        if(sqlSession == null|| testSqlSession(sqlSession)){
            sqlSession = sqlSessionFactory.openSession(true);
        }
        if(!testSqlSession(sqlSession)){
            throw new ServiceException("数据库连接有误");
        }
        return sqlSessionFactory.openSession(true);
    }

    public static void reLoadSession(){
        sqlSession = sqlSessionFactory.openSession(true);
    }

    public static boolean testSqlSession(SqlSession sqlSession){
        try{
            ChessMapper chessMapper = sqlSession.getMapper(ChessMapper.class);
            LOG.info(chessMapper.testConnect());
            return true;
        }catch (Exception e) {
            LOG.error(e);
            return false;
        }
    }

    public static <T> T getMapper(Class<T> t){
        return sqlSession.getMapper(t);
    }

}
